<template>
    <div  class="hb-tel-wrapper">
        <el-form :model="searchForm" label-position="top" :inline="true"  ref="searchForm">
            <el-row>
                <el-col :span="4">
                    <el-form-item label="慧拨号码: " prop="communicationNo">
                        <el-input v-model="searchForm.communicationNo" size="small" placeholder="请输入慧拨号码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态:" prop="phoneStatus">
                        <el-select v-model="searchForm.phoneStatus" size="small">
                           <!-- <el-option :key="item.key" v-for="item in phoneStatusList" :label="item.value" :value="item.key"></el-option>-->
                            <el-option label="全部" value=""></el-option>
                            <el-option label="被领取" value="379"></el-option>
                            <el-option label="空闲" value="380"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="归属人: " prop="memberName">
                        <el-input v-model="searchForm.memberName" size="small" placeholder="请输入归属人"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="领取时间: " prop="fetchTime">
                        <el-date-picker v-model="searchForm.fetchTime" size="small"
                                        type="daterange" @change="handlefetchTime"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="归还时间: " prop="returnTime">
                        <el-date-picker v-model="searchForm.returnTime" size="small"
                                        type="daterange" @change="handlereturnTime"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
            	<el-col :span="24" class="action_col">
            		<el-form-item class="action_button_group_open">
	                    <el-button type="primary" @click="clearFormData" icon="el-icon-delete" size="small" style="margin-bottom: 5px">清空筛选条件</el-button>
	                    <el-button type="primary" @click="fecthTelList" icon="el-icon-search" size="small">查询</el-button>
                	</el-form-item>
            	</el-col>
            </el-row>
        </el-form>
        <el-row>
            <el-button @click="dialogAdd = true" size="small" icon="el-icon-plus" >添加</el-button>
            <el-button size="small" @click="fecthTelList" ><i class="fa fa-refresh"></i> 刷新</el-button>
        </el-row>

        <el-table :data="telDataList" :default-sort = "{prop: 'fetchTime', order: 'descending'}"
                  border style="width: 100%;margin-top: 10px"  stripe highlight-current-row>
            <el-table-column prop="communicationNo" label="慧拨号码"  align="center"></el-table-column>
            <el-table-column prop="statusName" label="状态" align="center"></el-table-column>
            <el-table-column prop="memberName"  label="归属人" align="center"></el-table-column>
            <el-table-column width="210px" prop="fetchTime" sortable label="领取时间" align="center">
                <template scope="scope">
                    <span>{{scope.row.fetchTime | dateFormatter}}</span>
                </template>
            </el-table-column>
            <el-table-column width="210px" prop="returnTime" sortable label="归还时间" align="center">
                <template scope="scope">
                    <span>{{scope.row.returnTime | dateFormatter}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center">
                <template scope="scope">
                    <el-button @click="returnHBTel(scope.row)" v-if="scope.row.phoneStatus != 380" size="mini" type="primary" style="margin: 2px"><i class="fa fa-reply-all"></i> 归还</el-button>
                    <el-button @click="allocateHBTel(scope.row)" v-if="scope.row.phoneStatus == 380" size="mini" type="primary" style="margin: 2px"><i class="fa fa-share-alt"></i> 分配</el-button>
                    <el-button @click="delHBTel(scope.row)" v-if="scope.row.phoneStatus == 380" size="mini" icon="el-icon-delete" type="danger" style="margin: 2px">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pagination-bar" @size-change="handleTelSizeChange"
                       @current-change="handleTelCurrentChange"
                       :current-page="searchForm.pageNum"
                       :page-sizes="telPageSizes"
                       :page-size="searchForm.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="telTotal">
        </el-pagination>

        <el-dialog title="添加" :visible.sync="dialogAdd" size="tiny" @close="closeAddDialog">
            <el-row>
                <el-col :span="16">
                    <el-form :model="addForm" :rules="addTelRule" ref="addForm" label-position="top">
                        <el-form-item prop="communicationNo" label="慧拨号码: ">
                            <el-input @blur="validateTel" v-model="addForm.communicationNo" size="small" placeholder="请输入慧拨号码"></el-input>
                        </el-form-item>
                        <el-form-item label="归属人: ">
                            <el-input @focus="belongToDialog('add')" v-model="addMemberName" size="small" placeholder="请选择归属人"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <div slot="footer"  class="bottom-btn">
            	<el-button type="primary" class="top_save" @click="submitAddTel('addForm')" size="small"><i class="fa fa-save"></i> 保 存</el-button>
            	<el-button type="danger" class="top_close" @click="dialogAdd = false" size="small"><i class="fa fa-sign-out"></i> 取 消</el-button>
            </div>
        </el-dialog>

        <!--归属人弹框-->
        <el-dialog title="归属人" :visible.sync="dialogBelongTo" @close="closeDialog" >
            <el-row>
                <el-col :span="20">
                    <el-form label-position="right">
                        <el-form-item label="">
                            <el-input v-model="name" size="small" placeholder="请输入查询信息" style="width: 180px"></el-input>&nbsp;&nbsp;&nbsp;
                            <el-button type="primary" @click="query" icon="el-icon-search" size="small" > 查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <el-table :data="userDatas"  class="seller-table"
                      border style="width: 100%" highlight-current-row @current-change="highlightDialog" @row-click="selectUser">
                <el-table-column type="index" align="center" width="55"></el-table-column>
                <el-table-column prop="name" label="用户名" width="" align="center"></el-table-column>
                <el-table-column prop="account" label="账号" width="" align="center"></el-table-column>
                <el-table-column prop="departmentName" label="部门" align="center"></el-table-column>
                <el-table-column prop="communicationNo" label="慧拨号码" align="center"></el-table-column>
            </el-table>
            <div class="pagination-bar">
                <el-pagination @size-change="handleSizeChange"
                               @current-change="handleCurrentChange"
                               :current-page="currentPage"
                               :page-sizes="pageSizes"
                               :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="total">
                </el-pagination>
            </div>
            <div slot="footer"  class="bottom-btn">
            	<el-button type="primary" class="top_save" @click="selectSubmit" size="small"><i class="fa fa-save"></i> 保 存</el-button>
            	<el-button type="danger" class="top_close" @click="selectCancel" size="small"><i class="fa fa-sign-out"></i> 取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import Vue from 'vue'
    import { mapGetters } from 'vuex'
    import { Row,Col,Button,Input,Select,Option,DatePicker,FormItem,Form,Table,TableColumn,MessageBox,Message,Icon,Dialog,Tooltip,Pagination } from 'element-ui'
    import Cookie from 'js-cookie'
    import {validTel,getDate} from '~/utils/auth'

    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(DatePicker)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Icon)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Dialog)
    Vue.use(Tooltip)
    Vue.use(Pagination);

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    export default {
        head(){
            return {
                title: "呼叫系统管理"
            }
        },

        data () {
            return {
                tabName: '呼叫系统管理',
                searchForm: {
                    communicationNo: '',
                    phoneStatus: '',
                    memberName: '',
                    fetchTime: [],
                    fetchTimeStart: '',
                    fetchTimeEnd: '',
                    returnTime: [],
                    returnTimeStart: '',
                    returnTimeEnd: '',
                    pageSize: 50,
                    pageNum: 1
                },
                addForm: {
                    communicationNo: '',
                    memberId: ''
                },
                addMemberName: '',
                addTelRule: {
                    communicationNo: [{ required: true, message: '请输入慧拨电话号码' }]
                },
                telDataList: [],
                phoneStatusList: [],
                dialogAdd: false,
                dialogBelongTo: false,
                dialogCurrentRow: null,
                allocateUserId: '',
                allocateTelId: '',
                isAddFlag: false,
                userDatas: [],
                name: '',
                telTotal: 0,
                telPageSizes: [50,30,20,10],
                currentPage: 1,
                pageSizes: [10,20,30,50],
                pageSize: 10,
                total: 0,
                submitStatus: false
            }
        },
        computed: {
            ...mapGetters({
                'pageTabsList': 'getPageTabsList'
            })
        },
        filters: {
            dateFormatter(val) {
                return val ? getDate(new Date(val),true) : '-'
            }
        },
        methods: {
            selectSubmit() {
                if(!this.isAddFlag) {
                    //调用分配接口
                    this.$store.dispatch('allocatingHBTel',{id: this.allocateTelId,memberId: this.allocateUserId}).then(res => {
                        if(res.data&&res.data.code == 0) {
                            this.fecthTelList();
                            Message.success('分配成功')
                        }else{
                            // Message.error('分配失败')
                        }
                    })
                }
                this.isAddFlag = false;
                this.dialogBelongTo =  false;
            },
            selectCancel() {
                this.dialogBelongTo =  false;
                this.isAddFlag = false;
            },
            closeAddDialog() {
                this.$refs.addForm.resetFields();
                this.addMemberName = '';
                this.dialogAdd = false;
            },
            // 关闭dialog回调
            closeDialog () {
                this.dialogBelongTo = false;
                this.dialogCurrentRow = null;         // 清除高亮的行
                this.allocateUserId = '';      // 清除选择的用户
            },
            // dialog 用户列表单击选择高亮
            highlightDialog (val) {
                this.dialogCurrentRow = val;
            },
            // 选择分配到的用户
            selectUser (row, event, column) {
                if(row.communicationNo != null){
                    this.submitStatus = true;
                    Message.warning('您选择的用户已分配慧拨电话，请重新选择');
                    return false
                }
                this.submitStatus = false;
                if(this.isAddFlag) {
                    this.addForm.memberId = row.id;
                    this.addMemberName = row.name
                }else {
                    this.allocateUserId = row.id
                }
            },
            belongToDialog(str){
                this.isAddFlag = str == 'add' ? true : false;
                this.dialogBelongTo = true;
                this.query()
            },
            query() {
                this.$store.dispatch('getHBUserData',{
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    name: this.name
                }).then(res => {
                    if(res.data&&res.data.code == 0) {
                        let data = res.data.data;
                        this.userDatas = data.list;
                        this.pageSize = data.pageSize;
                        this.total = data.total;
                    }else{
                        this.userDatas = [];
                        this.currentPage = 1;
                        this.total = 0
                        //Message.error('获取用户列表失败')
                    }
                });
            },
            handleTelSizeChange(index){
                this.searchForm.pageSize = index;
                this.fecthTelList();
            },
            handleTelCurrentChange(index){
                this.searchForm.pageNum = index;
                this.fecthTelList()
            },
            handleCurrentChange(index){
                this.currentPage = index;
                this.query()
            },
            handleSizeChange(index) {
                this.pageSize = index;
                this.query()
            },
            handlefetchTime () {
                this.searchForm.fetchTimeStart = this.searchForm.fetchTime[0].getTime();
                this.searchForm.fetchTimeEnd = this.searchForm.fetchTime[1].getTime() + (23*60*60 + 59*60 + 59) * 1000;
            },
            handlereturnTime () {
                this.searchForm.returnTimeStart = this.searchForm.returnTime[0].getTime();
                this.searchForm.returnTimeEnd = this.searchForm.returnTime[1].getTime() + (23*60*60 + 59*60 + 59) * 1000;
            },
            //分配
            allocateHBTel(row){
                this.allocateTelId = row.id;
                this.belongToDialog('allocate')
            },
            returnHBTel(row) {
                this.$confirm('确定要归还慧拨号码'+row.communicationNo+'吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用归还接口
                    this.$store.dispatch('returnHBTel',{id: row.id}).then(res => {
                        if(res.data&&res.data.code == 0) {
                            this.fecthTelList();
                            Message.success('归还成功')
                        }else{
                            //Message.error('归还失败')
                        }
                    })
                }).catch(() => {
                        
                });
            },
            delHBTel(row) {
                this.$confirm('确定要删除慧拨号码'+row.communicationNo+'吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这里调用删除接口
                    this.$store.dispatch('deleteHBTel',{id: row.id}).then(res => {
                        if(res.data&&res.data.code == 0) {
                            this.fecthTelList();
                            Message.success('删除成功')
                        }else{
                            //Message.error('删除失败')
                        }
                    })
                }).catch(() => {
                        
                });
            },
            validateTel(){
                if(!validTel(this.addForm.communicationNo)){
                    Message.warning('请输入正确的号码')
                    return false
                }
                this.$store.dispatch('checkHBTel',{communicationNo: this.addForm.communicationNo})
                    .then(res => {
                        if(res.data&&res.data.code != 0) {
                            Message.error(this.addForm.communicationNo + '号码已存在')
                        }
                    })
            },
            submitAddTel(formName) {
                this.$refs[formName].validate((valid) => {
                        if (valid) {
                            if(!validTel(this.addForm.communicationNo)){
                                Message.warning('请输入正确的号码')
                                return false
                            }
                            this.$store.dispatch('insertHBTel',this.addForm).then(res => {
                                if(res.data&&res.data.code == 0) {
                                    this.fecthTelList();
                                    this.dialogAdd = false;
                                    Message.success('添加成功')
                                }else{
                                    //Message.error('添加失败')
                                }
                            })
                        }else {

                        }
                })
            },
            getOwnerData() {
                this.dialogVisible = true;
                this.getUserList();
                this.getOwnerDeptment();
            },
            fecthTelStatus() {
                this.$store.dispatch('telStatus').then(res => {
                    if(res.data&&res.data.data) {
                        this.phoneStatusList = res.data.data;
                    }else {
                        // Message.error('查询状态失败')
                    }
                })
            },
            fecthTelList() {
                this.$store.commit('TEL_SYSTEM_FILTER',{data: this.searchForm})
                this.$store.dispatch('searchTelList',{
                    communicationNo: this.searchForm.communicationNo,
                    phoneStatus: this.searchForm.phoneStatus,
                    memberName: this.searchForm.memberName,
                    fetchTimeStart: this.searchForm.fetchTimeStart,
                    fetchTimeEnd: this.searchForm.fetchTimeEnd,
                    returnTimeStart: this.searchForm.returnTimeStart,
                    returnTimeEnd: this.searchForm.returnTimeEnd,
                    pageSize: this.searchForm.pageSize,
                    pageNum: this.searchForm.pageNum
                }).then((res) => {
                    if(res.data && res.data.data) {
                        this.telDataList = res.data.data.list;
                        this.telTotal = res.data.data.total;
                    }else {
                        this.telDataList = [];
                        this.telTotal = 0;
                        // Message.error('查询电话列表失败')
                    }
                })
            },
            clearFormData() {
                this.$refs.searchForm.resetFields();
                this.searchForm.fetchTimeStart = '';
                this.searchForm.fetchTimeEnd = '';
                this.searchForm.returnTimeStart = '';
                this.searchForm.returnTimeEnd = '';
                this.$store.commit('TEL_SYSTEM_FILTER',{data: this.searchForm})
            }
        },
        created () {
            //this.fecthTelStatus();
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        },
        mounted() {
            if(this.$store.getters.telSystemFilter) {
                this.searchForm = this.$store.getters.telSystemFilter;
                if(this.searchForm.fetchTimeStart) {
                    this.searchForm.fetchTime = [new Date(this.searchForm.fetchTimeStart),new Date(this.searchForm.fetchTimeEnd)]
                }
                if(this.searchForm.returnTimeStart) {
                    this.searchForm.returnTime = [new Date(this.searchForm.returnTimeStart),new Date(this.searchForm.returnTimeEnd)]
                }
            }
            this.fecthTelList();
        }
    }

</script>

<style scoped lang="scss">
    .hb-tel-wrapper{
        margin-top: 20px;
    }
    .pagination-bar{
        margin-top: 12px;
        overflow: hidden;
        .el-pagination{
            float: left;
        }
    }
    .el-form {
        margin: 0 0 10px;
        .el-form-item {
            width: 70%
        }
        .el-input, .el-select, .el-cascader, .el-date-picker {
            width: 100%
        }

    }
    .bottom-btn{
        width:100%;
        display:table;
        text-align:center;
    }
    .signRow {
        background-color: #00ee00;
    }
</style>